package com.kob.botrunningsystem.Service.impl.utils;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author molimark<br />
 * @date: 2023/4/2 22:44<br/>
 * @description: <br/>
 */

public class BotPool extends Thread{
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    // 等价于消息队列
    private Queue<Bot> botQueue = new LinkedList<>(); // 不一定线程安全，自己管理成线程安全

    public void addBot(Integer userId,String botCode,String input){
        lock.lock();
        try {
            botQueue.add(new Bot(userId,botCode,input));
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    //若未来要改成不只是java代码的话，只需修改这个函数，如把代码放在docker里执行，这样c++也可以支持
    private void consume(Bot bot){
        Consumer consumer = new Consumer();
        consumer.startTimeout(2000,bot);
    }

    @Override
    public void run(){
        while(true){
            lock.lock();
            if(botQueue.isEmpty()){
                try {
                    // await执行后自动将锁释放，读写冲突才阻塞
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    lock.unlock();
                    break;
                }
            }else{
                Bot bot = botQueue.remove();
                lock.unlock();
                consume(bot); // 比较耗时，可能会执行几秒钟，因此要先解锁
            }
        }
    }
}
